
<script setup>
import getStatusHeight from '/utils/getStatusHeight.js';
import { onLoad } from "@dcloudio/uni-app"
import * as Api from '/api/questions';
import * as AudioApi from '/api/audio';
const {statusBarHeight,topBarHeight } = getStatusHeight()
import {ref,computed} from 'vue'
import { useCommonStore } from '/stores/common'
const common = useCommonStore()

let show = ref(false)
let show1 = ref(false)
function secondsToMinutesSeconds(seconds) {
  const minutes = Math.floor(seconds / 60); // 计算完整的分钟数
  const remainingSeconds = seconds % 60; // 计算剩余的秒数
  return `${towNum(minutes)}:${towNum(remainingSeconds)}`;
}
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
// innerAudioContext.src = "http://ws.stream.qqmusic.qq.com/C400001WYpTf3HTYrK.m4a?guid=397896146&vkey=596AE1EE9342FF0392CD934E735B6F01230F3DB3C52BCDC97A7D5843645EC88E534393B90DEEA5D569F2A47D5FCA07EF44CDAFD3BBDED4C5__v2b94c6e9&uin=&fromtag=120032&src=C400003Kdzcy1TuJCp.m4a"
innerAudioContext.onPlay(() => {
  console.log('开始播放');
});
innerAudioContext.onTimeUpdate(() => {
  timec.value= Math.floor(innerAudioContext.currentTime)
  timeb.value= secondsToMinutesSeconds(Math.floor(innerAudioContext.currentTime))
})
const sliderChange = (e) => {

  innerAudioContext.pause();

  innerAudioContext.seek(e.detail.value)
    innerAudioContext.play();


}
let ans = ref([0,["","","","","","","","","","","","","","","","","","","","","","","","",""],
  ["","","","","","","","","",""],["","","","","","","","","",""],["","","","",""]])

function towNum(num)
{
  if (num >= 10) {
    return num;
  } else {
    return '0' + num;
  }
}
let time = ref(0)
let timeb = ref(0)
let timec = ref(0)
function generateUUID() {
  // 1. 浏览器环境（H5）
  if (typeof window !== 'undefined' && window.crypto?.randomUUID) {
    return crypto.randomUUID();
  }

  // 2. 小程序/App环境（需兼容处理）
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}
const uuid = generateUUID()
innerAudioContext.onCanplay(() => {
  let intervalID = setInterval(() => {
    if (innerAudioContext.duration !== 0) {
      clearInterval(intervalID); // 清除定时器
      time.value=secondsToMinutesSeconds(Math.floor(innerAudioContext.duration))
      timeb.value=secondsToMinutesSeconds(Math.floor(innerAudioContext.currentTime))
    }
  }, 500);
  console.log(innerAudioContext.duration)
})
const status = ref(true)
function start() { //点击播放
  console.log("点击播放")
  if(!status.value) {
    innerAudioContext.play();
    status.value = true;
  }
}

function stop() { //点击暂停
  console.log("点击暂停")
  if(status.value) {
    innerAudioContext.pause();
    status.value = false;
  }
}
let i = ref(0)
const p = [1.0,1.25,1.5,2.0,0.5,0.8]
let pi = ref(1.0)
function playbackRate(){
  i.value = i.value + 1
  innerAudioContext.playbackRate = p[Math.floor(i.value%6)];
  pi.value = p[Math.floor(i.value%6)]
}
function closeShow(){
  show.value = false
}
let questionType = ref(0)
let questionList = ref([])
let id = ref()
let title = ref()
let tag = ref()
let content = ref()
let tid = ref(0)
onLoad(async (e)=>{
  common.score = 0
  common.time = 0
  setTimeout(() => {
    common.time = common.time + 1;
  }, 1000);
  if (e.tid){
    tid.value = e.tid
  }
  title.value = e.title
  questionType.value = e.type
  if (questionType.value == 1) tag.value = '听力'
  else if (questionType.value == 0) tag.value = '写作'
  else if (questionType.value == 2) tag.value = '选词填空'
  else if (questionType.value == 3) tag.value = '段落匹配'
  else if (questionType.value == 4) tag.value = '仔细阅读'
  else if (questionType.value == 5) tag.value = '翻译'
  id.value = e.id
  if (questionType.value == 1) {
    let title = await AudioApi.getAudio(e.title)
    let opt = await Api.getQuestions(e.id)
     questionList.value = JSON.parse(opt.data.opt)
    innerAudioContext.src = title.data[0].audio
  } else{
    let res = await Api.getQuestions(e.id)
    content.value = res.data.content
    questionList.value = JSON.parse(res.data.opt)
  }
})
function goBack(){
  uni.navigateBack();
}
let Wstrings = ref("")
let HearingActive = ref(0)
function last(){
  if (questionType.value == 1 && HearingActive.value > 0) HearingActive.value = HearingActive.value - 1
}
function next(){
  if (questionType.value == 1 && HearingActive.value < questionList.value.length-1) HearingActive.value = HearingActive.value + 1
}

function selected1(indx,idx){
  ans.value[1][indx] = idx
}
function selected2(indx,idx){
  ans.value[2][indx] = idx
}
function selected3(indx,idx){
  ans.value[3][indx] = idx
}
function selected4(indx,idx){
  ans.value[4][indx] = idx
}
function getToday() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}
async function submission() {
  uni.setStorageSync('time',  Number(uni.getStorageSync('time'))+common.time);
  if (uni.getStorageSync('qd')){
    if (uni.getStorageSync("qd") !== getToday()){
     uni.setStorageSync('qd1',Number(uni.getStorageSync('qd1'))+1)
     uni.setStorageSync('qd',getToday())
   }
  }else {
    uni.setStorageSync('qd1',1)
    uni.setStorageSync('qd',getToday())
  }
  common.fig = false
  if (questionType.value == 1){
    let res = await Api.submission({
      "title": title.value,
      "bankId": uuid,
      "stuId": uni.getStorageSync('userId').split(" ")[0],
      "type": 3,
      "questionId": id.value,
      "answer": ans.value[1].map(x => {
          if (x === 0) return "A"
          else if (x === 1) return "B"
          else if (x === 2) return "C"
          else if (x === 3) return "D"
          else return x
      }),
      "duringTime": Date.now(),
      "homeworkId": 0,
    })
    common.score = res.data.score
    common.sp = res.data.result
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }else if (questionType.value == 2){
    let res = await Api.submission({
      "title": title.value,
      "bankId": uuid,
      "stuId": uni.getStorageSync('userId').split(" ")[0],
      "type": 3,
      "questionId": id.value,
      "answer": ans.value[2].map(x => {
          if (x === 0) return "A"
          else if (x === 1) return "B"
          else if (x === 2) return "C"
          else if (x === 3) return "D"
          else if (x === 4) return "E"
          else if (x === 5) return "F"
          else if (x === 6) return "G"
          else if (x === 7) return "H"
          else if (x === 8) return "I"
          else if (x === 9) return "J"
          else if (x === 10) return "K"
          else if (x === 11) return "L"
          else if (x === 12) return "M"
          else if (x === 13) return "N"
          else if (x === 14) return "0"
      }),
      "duringTime": Date.now(),
      "homeworkId": 0,
    })
    common.score = res.data.score
    common.sp = res.data.result
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }else if (questionType.value == 3){
    let res = await Api.submission({
      "title": title.value,
      "bankId": uuid,
      "stuId": uni.getStorageSync('userId').split(" ")[0],
      "type": 3,
      "questionId": id.value,
      "answer": ans.value[3].map(x => {
          if (x === 0) return "A"
          else if (x === 1) return "B"
          else if (x === 2) return "C"
          else if (x === 3) return "D"
          else if (x === 4) return "E"
          else if (x === 5) return "F"
          else if (x === 6) return "G"
          else if (x === 7) return "H"
          else if (x === 8) return "I"
          else if (x === 9) return "J"
          else if (x === 10) return "K"
          else if (x === 11) return "L"
          else if (x === 12) return "M"
          else if (x === 13) return "N"
          else if (x === 14) return "0"
      }),
      "duringTime": Date.now(),
      "homeworkId":0,
    })
    common.score = res.data.score
    common.sp = res.data.result
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }else if (questionType.value == 4){
    let res = await Api.submission({
      "title": title.value,
      "bankId": uuid,
      "stuId": uni.getStorageSync('userId').split(" ")[0],
      "type": 3,
      "questionId": id.value,
      "answer": ans.value[4].map(x => {
          if (x === 0) return "A"
          else if (x === 1) return "B"
          else if (x === 2) return "C"
          else if (x === 3) return "D"
          else if (x === 4) return "E"
          else if (x === 5) return "F"
          else if (x === 6) return "G"
          else if (x === 7) return "H"
          else if (x === 8) return "I"
          else if (x === 9) return "J"
          else if (x === 10) return "K"
          else if (x === 11) return "L"
          else if (x === 12) return "M"
          else if (x === 13) return "N"
          else if (x === 14) return "0"
      }),
      "duringTime": Date.now(),
      "homeworkId": 0,
    })
    common.score = res.data.score
    common.sp = res.data.result
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }else if (questionType.value == 0){
    common.sp = []
    let res = await Api.submissionW1(content.value+' '+Wstrings.value)
    common.score = Wstrings.value === "" ? 0 : res.message
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }else if (questionType.value == 5){
    common.sp = []
    let res = await Api.submissionW2(content.value+' '+Wstrings.value)
    common.score =  Wstrings.value === "" ? 0 : res.message
    uni.redirectTo({
      url: '/pages/result/result'
    })
  }

}

const ss = ['A','B','C','D','E','F','G','H','I','J','K']
</script>

<template>
  <view :style="{'padding-top': statusBarHeight+'px',height: +topBarHeight+'px'}" style="background-color: white;display: flex;align-items: center;justify-content: flex-start;gap: 200rpx;padding-left: 30rpx">
    <van-icon @click="goBack" name="arrow-left" size="50rpx" /><view style="display: flex;align-items: center;gap: 10rpx"><van-icon name="clock-o" size="40rpx"/><van-count-down :time="1000*125*60" /></view>
  </view>
  <view style="display: flex;align-items: center;justify-content: space-between;padding: 10rpx 30rpx">
    <view style="display: flex;align-items: center;gap: 10rpx">
      <van-tag size="medium" type="success">{{tag}}</van-tag>
      <view style="font-size: 28rpx;color: #3F536E;opacity: 0.6">{{title}}</view>
    </view>
    <view style="font-size: 28rpx;color: #3F536E;opacity: 0.6"><text style="font-size: 32rpx;color: #0AD192"></text></view>
  </view>
  <view v-if="questionType == 1">
    <view style="background-color: #F6F8FC;height: 180rpx;width: 680rpx;margin: 20rpx auto;border-radius: 20rpx;display: flex;align-items: center;justify-content: center">
      <van-icon v-if="!status" @click="start" name="play-circle" color="#0AD192" size="40"/>
      <van-icon v-else name="pause-circle" color="#0AD192" size="40" @click="stop"/>
      <view style="display: flex;flex-direction: column;width: 400rpx">
        <slider :value="timec" :min='0' :max='innerAudioContext.duration.toFixed(0)' @change="sliderChange" :step="0.1" block-color="#0AD192" block-size="14" />
        <view style="font-size: 20rpx;color: #bcbcbc;margin: 0 36rpx">{{timeb ? timeb : '00:00'}}/{{time ? time : '00:00'}}</view>
      </view>
      <view @click="playbackRate()">
        <van-tag size="medium" type="success">{{pi}}x</van-tag>
      </view>

    </view>
    <scroll-view scroll-y style="height: calc(100vh - 540rpx);">
      <van-tabs :active="HearingActive" swipeable color = '#0AD192'>
        <van-tab v-for="(item,index) in questionList" :title="'题目'+(index+1)">
          <scroll-view scroll-y style="width: 700rpx;height: 660rpx;background-color: #F6F8FC;padding: 20rpx">
            <view @click="selected1(index,idx)" v-for="(it,idx) in item.split(',')" :class="{'select': idx.toString() == ans[1][index] }" style="background-color: white;padding: 40rpx;margin: 35rpx 20rpx;border-radius: 10rpx;min-height: 80rpx;line-height: 80rpx">
             {{it}}
            </view>
          </scroll-view>

        </van-tab>
      </van-tabs>
    </scroll-view>
  </view>


  <view v-if="questionType == 2" style="height: calc(100vh - 285rpx);background-color: #F6F8FC">
<scroll-view scroll-y :class="{'cont':!show}" style="height: 480rpx;">
  <view style="padding: 20rpx;background-color: #f6f8fc;font-size: 28rpx">
    {{content}}
  </view>

</scroll-view>

  </view>
  <van-popup
      v-if="questionType == 2"
      closeable
      :overlay="false"
      :show="show"
      position="bottom"
      round
      custom-style="height: 660rpx;"
      @close="closeShow"
  >
    <van-tabs swipeable color = '#0AD192'>
      <van-tab v-for="(item,index) in questionList.slice(0, 10)" :title="index+1">
        <scroll-view scroll-y style="width: 700rpx;height: 520rpx;background-color: #F6F8FC;padding: 20rpx;">
          <view style="display: flex;flex-wrap: wrap;gap: 20rpx">
            <view  @click="selected2(index,idx)"  v-for="(item1,idx) in questionList" :class="{'select': idx.toString() == ans[2][index] }" style="width: 340rpx;height: 100rpx;background-color: white;font-size: 26rpx;line-height: 100rpx;text-align: center;border-radius: 10rpx">
              {{item1}}
            </view>
          </view>

        </scroll-view>

      </van-tab>
    </van-tabs>
<!--    <van-icon name="arrow-down" />-->
  </van-popup>

  <view v-if="questionType == 3" style="height: calc(100vh - 285rpx);background-color: #F6F8FC">
<scroll-view scroll-y :class="{'cont':!show}" style="height: 480rpx;">
  <view style="padding: 20rpx;background-color: #f6f8fc;font-size: 28rpx">
    {{content}}
  </view>

</scroll-view>

  </view>
  <van-popup
      v-if="questionType == 3"
      closeable
      :overlay="false"
      :show="show"
      position="bottom"
      round
      custom-style="height: 660rpx;"
      @close="closeShow"
  >
    <van-tabs swipeable color = '#0AD192'>
      <van-tab v-for="(item,index) in questionList" :title="index+1">
        <scroll-view scroll-y style="width: 700rpx;height: 520rpx;background-color: #F6F8FC;padding: 20rpx">
          <view style="min-height: 80rpx;font-size: 26rpx;color: #8a8a8a">
            {{item}}
          </view>
          <view style="display: flex;flex-wrap: wrap;gap: 30rpx;margin-top: 20rpx;padding: 10rpx 20rpx">
            <view v-for="(item,idx) in ss" @click="selected3(index,idx)" :class="{'select': idx.toString() == ans[3][index] }" style="width: 100rpx;height: 100rpx;border-radius: 50%;background-color: #fff;box-shadow: 0 0 10rpx rgba(0,0,0,0.1);text-align: center;line-height: 100rpx">{{item}}</view>
          </view>

        </scroll-view>

      </van-tab>
    </van-tabs>
<!--    <van-icon name="arrow-down" />-->
  </van-popup>




  <view v-if="questionType == 4" style="height: calc(100vh - 285rpx);background-color: #F6F8FC">
    <scroll-view scroll-y :class="{'cont':!show}" style="height: 480rpx;">
      <view style="padding: 20rpx;background-color: #f6f8fc;font-size: 28rpx">
        {{content}}
      </view>

    </scroll-view>

  </view>
  <van-popup
      v-if="questionType == 4"
      closeable
      :overlay="false"
      :show="show"
      position="bottom"
      round
      custom-style="height: 660rpx;"
      @close="closeShow"
  >
    <van-tabs swipeable color = '#0AD192'>
      <van-tab v-for="(item,index) in questionList" :title="index+1">
        <scroll-view scroll-y style="width: 700rpx;height: 520rpx;background-color: #F6F8FC;padding: 20rpx">
          <view style="min-height: 80rpx;font-size: 26rpx;color: #8a8a8a">
            {{item.title}}
          </view>
          <view @click="selected4(index,idx)" :class="{'select': idx.toString() == ans[4][index] }" v-for="(p,idx) in item.select" style="background-color: white;padding: 20rpx;margin: 35rpx 20rpx;border-radius: 10rpx;min-height: 60rpx;line-height: 80rpx">
            {{p}}
          </view>
        </scroll-view>

      </van-tab>
    </van-tabs>
    <!--    <van-icon name="arrow-down" />-->
  </van-popup>


    <view v-if="questionType==0 || questionType==5" style="height: calc(100vh - 285rpx);background-color: #f6f8fc">
      <view style="padding: 20rpx;background-color: #f6f8fc;font-size: 28rpx">{{content}}</view>
<!--      <van-field-->
<!--          :value="Wstrings"-->
<!--          label="内容"-->
<!--          type="textarea"-->
<!--          placeholder="请输入"-->
<!--          autosize-->
<!--          :border="false"-->
<!--      />-->
      <textarea :maxlength="-1" v-model="Wstrings"  style="height: 400rpx;border-radius: 10rpx;width: 700rpx;padding: 20rpx 10rpx;background-color: #f3f2f2;margin: 0 auto" placeholder="请输入内容"/>
    </view>
  <view style="z-index: -1;height: 100rpx;display: flex;align-items: center;justify-content: space-around" v-if="!show">
    <view style="display: flex;align-items: center;gap: 100rpx">
            <view @click="show = !show" v-if="questionType != 1 && questionType !=0 && questionType !=5">
              <van-icon name="records-o" size="55rpx"/>
              <view style="font-size: 22rpx;color: #3F536E;opacity: 0.6">作答</view>
            </view>
      <view>
        <van-icon name="completed-o" size="55rpx"/>
        <view style="font-size: 22rpx;color: #3F536E;opacity: 0.6">答题卡</view>
      </view>


    </view>

    <view style="display: flex;align-items: center;gap: 40rpx">
      <van-button  round hairline  color="#0AD192" @click="last" v-if="questionType == 1">上一题</van-button>
      <van-button round hairline color="#0AD192" @click="next" v-if="questionType == 1">下一题</van-button>
      <van-button round hairline color="#0AD192" @click="submission" > 交 卷 </van-button>
    </view>

  </view>
</template>

<style scoped>
.cont{
  height: calc(100vh - 285rpx) !important;
}
.select{
  background-color: #0AD192 !important;
  color: #fff;
}
</style>
